package com.itheima.controller;

import com.itheima.common.constant.MessageConstant;
import com.itheima.common.constant.RedisMessageConstant;
import com.itheima.common.entity.Result;
import com.itheima.common.pojo.Order;
import com.itheima.common.pojo.Reservation;
import com.itheima.service.OrderService;
import com.itheima.service.OrderSettingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/order")
@CrossOrigin
@Slf4j
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderSettingService orderSettingService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 体检预约
     */
    @PostMapping("/submitOrder")
    public Result submitOrder(@RequestBody Reservation reservation) {
        // 1. 验证基本参数
        if (reservation == null) {
            return new Result(false, "预约信息不能为空");
        }
        if (!StringUtils.hasText(reservation.getValidateCode())) {
            return new Result(false, "验证码不能为空");
        }

        // 2. 验证码校验 - 使用正确的Redis常量
        String redisCode = redisTemplate.opsForValue().get(
            RedisMessageConstant.SENDTYPE_ORDER + reservation.getTelephone());
        if (redisCode == null) {
            return new Result(false, "验证码已过期，请重新获取");
        }
        if (!redisCode.equals(reservation.getValidateCode())) {
            return new Result(false, "验证码错误");
        }

        try {
            // 3. 调用服务完成预约
            orderService.submitOrder(reservation);
            
            // 4. 预约成功后删除验证码
            redisTemplate.delete(RedisMessageConstant.SENDTYPE_ORDER + reservation.getTelephone());
            
            return new Result(true, MessageConstant.ORDER_SUCCESS);
        } catch (RuntimeException e) {
            return new Result(false, e.getMessage());
        } catch (Exception e) {
            log.error("预约失败", e);
            return new Result(false, MessageConstant.ORDER_FAIL);
        }
    }

    /**
     * 根据预约id查询预约信息
     * @param id
     * @return
     */
    @PostMapping("/findById")
    public Result findById(@RequestParam Integer id){
        log.info("根据id查询预约信息:{}",id);
        Order order = orderSettingService.findById(id);
        return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,order);
    }
}
